package edu.nf.project.services.socket;

import com.fasterxml.jackson.databind.ObjectMapper;
import edu.nf.project.entitys.entity.other.Message;
import edu.nf.project.services.other.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ChatWebSocket implements WebSocketHandler {
    // 用于存储所有连接的客户端
    private static final Map<String, WebSocketSession> CLIENTS = new ConcurrentHashMap<>();
    
    @Autowired
    private MessageService messageService;
    
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        String userId = getUserIdFromSession(session);
        CLIENTS.put(userId, session);
        System.out.println("用户 " + userId + " 已连接");
        System.out.println("当前在线用户数: " + CLIENTS.size());
        System.out.println("在线用户列表: " + CLIENTS.keySet());
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) {
        try {
            String payload = message.getPayload().toString();
            System.out.println("收到消息: " + payload);
            Map<String, Object> messageMap = objectMapper.readValue(payload, Map.class);
            String type = (String) messageMap.get("type");
            
            if ("init".equals(type)) {
                // 处理初始化消息
                String userId = (String) messageMap.get("userId");
                System.out.println("用户 " + userId + " 初始化连接");
                return;
            }
            
            if ("message".equals(type)) {
                // 创建消息对象
                Message chatMessage = new Message();
                chatMessage.setSender((String) messageMap.get("sender"));
                chatMessage.setReceiver((String) messageMap.get("receiver"));
                chatMessage.setContent((String) messageMap.get("content"));
                // 将时间戳转换为Date对象
                Long timestamp = (Long) messageMap.get("sendTime");
                chatMessage.setSendTime(new Date(timestamp));
                
                System.out.println("准备发送消息: " + chatMessage);
                
                // 保存消息到数据库
                messageService.sendMessage(chatMessage);
                System.out.println("消息已保存到数据库");
                
                // 只发送消息给接收者
                WebSocketSession receiverSession = CLIENTS.get(chatMessage.getReceiver());
                if (receiverSession != null && receiverSession.isOpen()) {
                    receiverSession.sendMessage(new TextMessage(payload));
                    System.out.println("消息已发送给接收者: " + chatMessage.getReceiver());
                } else {
                    System.out.println("接收者不在线: " + chatMessage.getReceiver());
                }
            }
        } catch (Exception e) {
            System.err.println("处理消息时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) {
        String userId = getUserIdFromSession(session);
        CLIENTS.remove(userId);
        System.err.println("用户 " + userId + " 连接异常: " + exception.getMessage());
        System.out.println("当前在线用户数: " + CLIENTS.size());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        String userId = getUserIdFromSession(session);
        CLIENTS.remove(userId);
        System.out.println("用户 " + userId + " 已断开连接，状态: " + status);
        System.out.println("当前在线用户数: " + CLIENTS.size());
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    private String getUserIdFromSession(WebSocketSession session) {
        String path = session.getUri().getPath();
        return path.substring(path.lastIndexOf('/') + 1);
    }
} 